﻿using System;
using System.Linq;
using System.Linq.Expressions;
using ASPItalia.ModelVirtualCasting.Common;
using ASPItalia.ModelVirtualCasting.ObjectModel;

namespace ASPItalia.ModelVirtualCasting.EntityFramework
{
    public class ModelRepository : BaseRepository<Candidate>, IModelRepository
    {
        public ModelRepository(IContextContainer container) : base(container) { }

        public void InsertOnSubmit(Model entity)
        {
            throw new NotImplementedException();
        }

        public void Update(Model entity)
        {
            Context.People.Attach(entity);
            Context.ObjectStateManager.GetObjectStateEntry(entity).SetModified();
        }

        public void DeleteOnSubmit(Model entity)
        {
            Context.People.DeleteObject(entity);
        }

        public void SubmitChanges()
        {
            base.SaveChanges();
        }

        public IQueryable<ModelDTO> GetRandomModels(int number)
		{
            var query = (from m in CurrentObjectQuery.OfType<Model>()
                        select new ModelDTO { 
                            Age = DateTime.Today.Year - m.BirthDate.Year,
                            Country = m.ResidenceCountry.CountryName,
                            NickName = m.NickName,
                            ImageUrl = m.Multimedia.Where(image => image is Image).FirstOrDefault().FileName
                        }).Take(number);

            return query;
		}

        public IQueryable<Model> GetAll()
        {
            return CurrentObjectQuery.OfType<Model>();
        }

        public IQueryable<Model> Where(Expression<Func<Model, bool>> predicate)
        {
            return CurrentObjectQuery.OfType<Model>().Where(predicate);
        }

        public long Count(Expression<Func<Model, bool>> predicate)
        {
            return CurrentObjectQuery.OfType<Model>().Count(predicate);
        }

        public IModelRepository Include(params string[] paths)
        {
            CurrentObjectQuery = CreateObjectQuery().Include(paths);
            return this;
        }

				#region IReadOnlyRepository<IModelRepository,Model> Members


				public IModelRepository EnableLazyLoading()
				{
					SetLazyLoading(true);
					return this;
				}

				public IModelRepository DisableLazyLoading()
				{
					SetLazyLoading(false);
					return this;
				}

				#endregion
		}
}